﻿using System.IO;
using System.Linq;
using System.ServiceModel.Activation;
using System.Web.Hosting;

namespace GroupChallenge.Web
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PlayerAdminService : IPlayerAdminService
    {
        // Saves the player image data and returns a player image id that the player can user to play.
        public int SavePlayerImage(byte[] imageData)
        {
            return SavePlayerImageData(imageData);
        }

        // Saves the player image data and returns a player image id that the player can user to play.
        private static int SavePlayerImageData(byte[] imageData)
        {
            int ret = 0;

            if (null == imageData)
                return ret;
            string filePrefix = "Player_";

            string filePathToWrite = AuthorizedPlayerImagesFolder();
            string[] files = Directory.GetFiles(filePathToWrite, filePrefix + "*.jpg", SearchOption.TopDirectoryOnly);

            // Return the next file id that's not found.
            ret = (files.Select(file => (int?)int.Parse(Path.GetFileNameWithoutExtension(file).Substring(filePrefix.Length))).Max() ?? 0) + 1;
            string fileName = Path.Combine(filePathToWrite, string.Format("{0}{1}.jpg", filePrefix, ret));
            File.WriteAllBytes(fileName, imageData);

            return ret;
        }

        // Return the folder for player image files.
        private static string AuthorizedPlayerImagesFolder()
        {
            return HostingEnvironment.MapPath("~/PlayerImages");
        }
    }
}
